﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using WpfClient.Command;

namespace WpfClient
{
    public class WpfClientViewModel : INotifyPropertyChanged, IDisposable
    {
        private bool disposed; 

        private CollectionView subscribers;
        private ObservableCollection<DataFeedSubscriber> listSubscriber;

        public WpfClientViewModel()
        {
            listSubscriber = new ObservableCollection<DataFeedSubscriber>();
            Subscribers = (CollectionView)CollectionViewSource.GetDefaultView(listSubscriber);

            disposed = false;

            AddCommand = new MvvmCommand(arg =>
            {
                DataFeedSubscriber s = new DataFeedSubscriber();
                listSubscriber.Add(s);

                s.Subscribe();

                //Subscribers = (CollectionView)CollectionViewSource.GetDefaultView(listSubscriber);
            }, arg =>
            { return true; });

            CancelCommand = new MvvmCommand(arg =>
            {
                if (Subscribers.CurrentItem != null)
                {
                    var subscriber = Subscribers.CurrentItem as DataFeedSubscriber;
                    subscriber.Dispose();

                    listSubscriber.Remove(subscriber);
                }
            }, arg =>
            { return true; });
        }

        public ICommand AddCommand { get; private set; }
        public ICommand CancelCommand { get; private set; }

        public CollectionView Subscribers
        {
            get { return subscribers; }
            set
            {
                subscribers = value;
                OnPropertyChanged("Subscribers");
            }
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                this.PropertyChanged(this, e);
            }
        } 
        #endregion

        #region IDisposable
        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // Dispose Managed Resource 
                }

                listSubscriber.ToList().ForEach(subscriber => subscriber.Dispose());

                disposed = true;
            }
        } 
        #endregion
    }
}
